package com.example.treehole.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.treehole.R;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.example.treehole.entity.UserEntity;
import com.example.treehole.entity.UserResponse;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnLvItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class EditInfoActivity extends BaseActivity {

    @BindView(R.id.iv_exit)
    ImageView ivExit;
    @BindView(R.id.tv_head_line)
    TextView tvHeadLine;
    @BindView(R.id.top_navigation_bar)
    LinearLayout topNavigationBar;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_gender)
    EditText etGender;
    @BindView(R.id.et_sno)
    EditText etSno;
    @BindView(R.id.et_real_name)
    EditText etRealName;
    @BindView(R.id.et_phone)
    EditText etPhone;

    UserEntity userEntity;

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.rl_header,R.id.iv_exit,R.id.btn_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_exit:
                finish();
                break;
            case R.id.btn_save:
                finish();
                break;
            case R.id.rl_header:
                showDialog();
        }
    }


    private void showDialog() {
            CircleDialog.Builder builder = new CircleDialog.Builder();
            List<String> list = new ArrayList<>();
            list.add("相册选择");
            list.add("拍照选择");
            builder.setGravity(Gravity.BOTTOM)
                    .setWidth(getWindowManager().getDefaultDisplay().getWidth())
                    .setItems(list, new OnLvItemClickListener() {
                        @SuppressLint("CheckResult")
                        @Override
                        public boolean onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if (position == 0) {
                                PictureSelector.create(EditInfoActivity.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .compress(false)
                                        .maxSelectNum(1)
                                        .minSelectNum(1)
                                        .imageSpanCount(3)
                                        .selectionMode(PictureConfig.MULTIPLE)
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            } else {
                                //获取写的权限
                                RxPermissions rxPermission = new RxPermissions(EditInfoActivity.this);
                                rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .subscribe(new Consumer<Permission>() {
                                            @SuppressLint("CheckResult")
                                            @Override
                                            public void accept(Permission permission) {
                                                if (permission.granted){
                                                    PictureSelector.create(EditInfoActivity.this)
                                                            .openCamera(PictureMimeType.ofImage())
                                                            .compress(true)
                                                            .forResult(PictureConfig.CHOOSE_REQUEST);
                                                }
                                            }
                                        });
                            }
                            return true;
                        }
                    })
                    .setNegative("取消", null)
                    .show(getSupportFragmentManager());
        }


    @SuppressLint("HandlerLeak")
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                showData();
            }
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.activity_edit_info;
    }

    @Override
    protected void initData() {
        tvHeadLine.setText(getString(R.string.edit_info));
        loadData();
    }

    private void loadData() {
        String userId = getStringFromSp("id");
        Api.config(ApiConfig.GET_USER + "/" + userId, new HashMap<>()).getRequest(this, new Callback() {
            @Override
            public void onSuccess(String res) {
                try {
                    UserResponse userResponse = new Gson().fromJson(res, UserResponse.class);
                    userEntity = userResponse.getUserEntity();
                    mHandler.sendEmptyMessage(1);
                } catch (JsonSyntaxException e) {
                    showToastSync(getString(R.string.load_error));
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    private void showData() {
        etName.setText(userEntity.getName());
        etGender.setText(userEntity.getSex()==1?"男":"女");
        etSno.setText(userEntity.getStuId());
        etPhone.setText(userEntity.gettPhone());
        //姓名
    }
}